package com.zheng.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zheng.common.Result;
import com.zheng.entity.News;
import com.zheng.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;


    @GetMapping
    public Result<?> selectAll(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam String search,@RequestParam String option){
        Page<News> page = new Page<>(pageNum, pageSize);
        QueryWrapper<News> wrapper =new QueryWrapper<>();
        if(StrUtil.isNotBlank(search)){
            wrapper.like(option, search);
        }

        Page<News> newsPage = newsService.page(page, wrapper);
        return Result.success(newsPage);
    }

    @PostMapping
    public Result<?> save(@RequestBody News news){
        news.setTime(new Date());
        newsService.save(news);
        return Result.success();
    }


    @PutMapping
    public Result<?> updateNews(@RequestBody News news){
        newsService.updateById(news);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> deleteNews(@PathVariable Long id){
        newsService.removeById(id);
        return Result.success();
    }


}
